import { FormItem, CustomEnum, FormPageItem } from 'custom/index'
import { FormItemRule } from 'element-plus'
import { Arrayable } from 'element-plus/es/utils/typescript.mjs';

export default class FormPageFormItem extends FormItem {
  public static name: CustomEnum = 'FormPageFormItem';

  label(label: string) {
    const parent = this.parent as FormPageItem
    if (!parent) return this
    parent.label(label)
    return this
  }

  span(span: number) {
    const parent = this.parent as FormPageItem
    if (!parent) return this
    parent.span(span)
    return this
  }

  required(msg: string = '', trigger?: 'blur' | 'change') {
    const parent = this.parent as FormPageItem
    if (!parent) return this
    parent.required(msg, trigger)
    return this
  }

  rules(rules: Arrayable<FormItemRule>) {
    const parent = this.parent as FormPageItem
    if (!parent) return this
    parent.rules(rules)
    return this
  }

  validator(validator: any, rule = {}) {
    return this.rules({ ...rule, validator: (rule: any, value: any, cb: any) => {
      validator(rule, value, cb, (this.instance as any)?.data)
    }})
  }

  atLeastOne(fieldA: string, fieldB: string, errorMsg = '请至少填写一项') {
    return this.rules({
      validator: (rule: any, value: any, callback: (error?: Error) => void) => {
        const form = (this.instance as any)?.data || {}
        if (!value && !form[fieldB]) {
          callback(new Error(errorMsg))
        } else {
          callback()
        }
      }
    })
  }

  end() {
    return this.upto('FormPageGroup')
  }

}
